﻿/**
 * Copyright (C) 2012 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Spi;
using NGuice.Inject.Internal.Util;
using System.Collections;

namespace NGuice.Inject.Internal
{
    //complete!
    /// <summary>
    /// 此类同时扮演值对象和构建器的角色。当获取Elements时，一个不可变的元素集合被构造且原始的
    /// 可变列表至null，类似的，暴露的keys也被构建为不可变的
    /// </summary>
    public sealed class PrivateElementsImpl : IPrivateElements
    {
        private readonly object source;

        private IList<IElement> elementsMutable = Lists.NewArrayList<IElement>();

        //private IList<ExposureBuilder<?>> exposureBuilders = Lists.NewArrayList();
        private IList<ExposureBuilder> exposureBuilders = Lists.NewArrayList<ExposureBuilder>();//存储所有ExposureBuilder

        private ImmutableList<IElement> elements;

        private IDictionary<Key, object> exposedKeysToSources;

        private Injector injector;

        public PrivateElementsImpl(object source)
        {
            this.source = Preconditions.CheckNotNull(source, "source");
        }

        public object Source
        {
            get { return source; }
        }

        public IList<IElement> Elements
        {
            get
            {
                if (elements == null)
                {
                    elements = ImmutableList<IElement>.CopyOf<IElement>(elementsMutable);
                    elementsMutable = null;
                }
                return elements;
            }
        }

        public Injector Injector
        {
            get { return injector; }
        }

        public void InitInjector(Injector injector)
        {
            Preconditions.CheckState(this.injector == null, "injector already initialized");
            this.injector = Preconditions.CheckNotNull(injector, "injector");
        }

        public ISet<Key> GetExposedKeys()
        {
            if (exposedKeysToSources == null)
            {
                IDictionary<Key, object> exposedKeysToSourcesMutable = new SortedList<Key, object>();
                foreach (ExposureBuilder exposureBuilder in exposureBuilders)
                {
                    exposedKeysToSourcesMutable.Add(exposureBuilder.Key, exposureBuilder.Source);
                }
                exposedKeysToSources = ImmutableDictionary<Key, object>.CopyOf(exposedKeysToSourcesMutable);
                exposureBuilders = null;
            }
            return new HashSet<Key>(exposedKeysToSources.Keys);
        }

        public T AcceptVisitor<T>(IElementVisitor<T> visitor)
        {
            return visitor.Visit(this);
        }

        public IList<IElement> GetElementsMutable()
        {
            return elementsMutable;
        }

        public void AddExposureBuilder(ExposureBuilder exposureBuilder)
        {
            exposureBuilders.Add(exposureBuilder);
        }

        public void ApplyTo(IBinder binder)
        {
            IPrivateBinder privateBinder = binder.WithSource(source).NewPrivateBinder();

            foreach (IElement element in Elements)
            {
                element.ApplyTo(privateBinder);
            }

            GetExposedKeys(); // ensure exposedKeysToSources is populated
            foreach (Key key in exposedKeysToSources.Keys)
            {
                privateBinder.WithSource(exposedKeysToSources[key]).Expose(key);
            }
        }

        public object GetExposedSource<T>(Key<T> key)
        {
            GetExposedKeys(); // ensure exposedKeysToSources is populated
            object source = exposedKeysToSources[key];
            Preconditions.CheckArgument(source != null, "%s not exposed by %s.", key, this);
            return source;
        }

        public object GetExposedSource(Key key)
        {
            GetExposedKeys(); // ensure exposedKeysToSources is populated
            object source = exposedKeysToSources[key];
            Preconditions.CheckArgument(source != null, "%s not exposed by %s.", key, this);
            return source;
        }

        public string ToString()
        {
            return new ToStringBuilder(typeof(IPrivateElements))
                .Add("exposedKeys", GetExposedKeys())
                .Add("source", Source)
                .ToString();
        }

    }
}
